package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.EmpCertificate;
import com.example.entity.EmpEducation;
import com.example.entity.EmpWorkHistory;
import com.example.entity.Employee;
import com.example.dto.EmployeeDTO;
import com.example.dto.EmployeeQuery;
import com.example.mapper.EmpCertificateMapper;
import com.example.mapper.EmpEducationMapper;
import com.example.mapper.EmpWorkHistoryMapper;
import com.example.mapper.EmployeeMapper;
import com.example.service.EmployeeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Date;

@Service
@RequiredArgsConstructor
@Slf4j
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    private final EmpEducationMapper educationMapper;
    private final EmpWorkHistoryMapper workHistoryMapper;
    private final EmpCertificateMapper certificateMapper;

    @Override
    public Page<Employee> page(Page<Employee> page, EmployeeQuery query) {
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        // 构建查询条件
        if (query.getName() != null && !query.getName().isEmpty()) {
            wrapper.like(Employee::getName, query.getName());
        }
        if (query.getDeptId() != null) {
            wrapper.eq(Employee::getDeptId, query.getDeptId());
        }
        if (query.getStatus() != null) {
            wrapper.eq(Employee::getStatus, query.getStatus());
        }
        // 按入职日期降序排序
        wrapper.orderByDesc(Employee::getEntryDate);
        
        return page(page, wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public EmployeeDTO getEmployeeById(Long id) {
        // 获取员工基本信息
        Employee employee = getById(id);
        if (employee == null) {
            return null;
        }
        
        // 构建DTO
        EmployeeDTO dto = new EmployeeDTO();
        // 复制基本信息
        dto.setEmployee(employee);
        // 获取教育经历
        dto.setEducationList(getEducationList(id));
        // 获取工作经历
        dto.setWorkHistoryList(getWorkHistoryList(id));
        // 获取证书信息
        dto.setCertificateList(getCertificateList(id));
        
        return dto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long addEmployee(EmployeeDTO dto) {
        // 保存员工基本信息
        Employee employee = dto.getEmployee();
        save(employee);
        
        Long employeeId = employee.getId();
        
        // 保存教育经历
        if (dto.getEducationList() != null) {
            for (EmpEducation education : dto.getEducationList()) {
                education.setEmpId(employeeId);
                educationMapper.insert(education);
            }
        }
        
        // 保存工作经历
        if (dto.getWorkHistoryList() != null) {
            for (EmpWorkHistory workHistory : dto.getWorkHistoryList()) {
                workHistory.setEmpId(employeeId);
                workHistoryMapper.insert(workHistory);
            }
        }
        
        // 保存证书信息
        if (dto.getCertificateList() != null) {
            for (EmpCertificate certificate : dto.getCertificateList()) {
                certificate.setEmpId(employeeId);
                certificateMapper.insert(certificate);
            }
        }
        
        return employeeId;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateEmployee(EmployeeDTO dto) {
        // 更新员工基本信息
        updateById(dto.getEmployee());
        
        Long employeeId = dto.getEmployee().getId();
        
        // 更新教育经历
        if (dto.getEducationList() != null) {
            // 先删除原有记录
            educationMapper.delete(new LambdaQueryWrapper<EmpEducation>()
                    .eq(EmpEducation::getEmpId, employeeId));
            
            // 添加新记录
            for (EmpEducation education : dto.getEducationList()) {
                education.setEmpId(employeeId);
                educationMapper.insert(education);
            }
        }
        
        // 更新工作经历
        if (dto.getWorkHistoryList() != null) {
            // 先删除原有记录
            workHistoryMapper.delete(new LambdaQueryWrapper<EmpWorkHistory>()
                    .eq(EmpWorkHistory::getEmpId, employeeId));
            
            // 添加新记录
            for (EmpWorkHistory workHistory : dto.getWorkHistoryList()) {
                workHistory.setEmpId(employeeId);
                workHistoryMapper.insert(workHistory);
            }
        }
        
        // 更新证书信息
        if (dto.getCertificateList() != null) {
            // 先删除原有记录
            certificateMapper.delete(new LambdaQueryWrapper<EmpCertificate>()
                    .eq(EmpCertificate::getEmpId, employeeId));
            
            // 添加新记录
            for (EmpCertificate certificate : dto.getCertificateList()) {
                certificate.setEmpId(employeeId);
                certificateMapper.insert(certificate);
            }
        }
    }
    
    /**
     * 修改员工信息
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean updateEmployee(Employee employee, List<EmpEducation> educationList, 
                                 List<EmpWorkHistory> workHistoryList, List<EmpCertificate> certificateList) {
        try {
            // 保存员工基本信息
            updateById(employee);
            Long employeeId = employee.getId();
            
            // 更新教育经历
            educationMapper.delete(new LambdaQueryWrapper<EmpEducation>()
                    .eq(EmpEducation::getEmpId, employeeId));
            if (educationList != null && !educationList.isEmpty()) {
                for (EmpEducation education : educationList) {
                    education.setEmpId(employeeId);
                    educationMapper.insert(education);
                }
            }
            
            // 更新工作经历
            workHistoryMapper.delete(new LambdaQueryWrapper<EmpWorkHistory>()
                    .eq(EmpWorkHistory::getEmpId, employeeId));
            if (workHistoryList != null && !workHistoryList.isEmpty()) {
                for (EmpWorkHistory workHistory : workHistoryList) {
                    workHistory.setEmpId(employeeId);
                    workHistoryMapper.insert(workHistory);
                }
            }
            
            // 更新证书信息
            certificateMapper.delete(new LambdaQueryWrapper<EmpCertificate>()
                    .eq(EmpCertificate::getEmpId, employeeId));
            if (certificateList != null && !certificateList.isEmpty()) {
                for (EmpCertificate certificate : certificateList) {
                    certificate.setEmpId(employeeId);
                    certificateMapper.insert(certificate);
                }
            }
            
            return true;
        } catch (Exception e) {
            log.error("修改员工信息失败", e);
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteEmployee(Long id) {
        doDeleteEmployee(id);
    }
    
    /**
     * 删除员工信息 - 提供布尔返回值版本
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteEmployeeAndReturnStatus(Long employeeId) {
        try {
            doDeleteEmployee(employeeId);
            return true;
        } catch (Exception e) {
            log.error("删除员工失败", e);
            return false;
        }
    }
    
    /**
     * 执行删除员工的具体操作
     */
    private void doDeleteEmployee(Long employeeId) {
        // 删除员工基本信息
        removeById(employeeId);
        
        // 删除教育经历
        educationMapper.delete(new LambdaQueryWrapper<EmpEducation>()
                .eq(EmpEducation::getEmpId, employeeId));
        
        // 删除工作经历
        workHistoryMapper.delete(new LambdaQueryWrapper<EmpWorkHistory>()
                .eq(EmpWorkHistory::getEmpId, employeeId));
        
        // 删除证书信息
        certificateMapper.delete(new LambdaQueryWrapper<EmpCertificate>()
                .eq(EmpCertificate::getEmpId, employeeId));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDeleteEmployee(List<Long> ids) {
        // 批量删除员工基本信息
        removeByIds(ids);
        
        // 批量删除关联数据
        // 可以通过 in 条件一次性删除
        educationMapper.delete(new LambdaQueryWrapper<EmpEducation>()
                .in(EmpEducation::getEmpId, ids));
        
        workHistoryMapper.delete(new LambdaQueryWrapper<EmpWorkHistory>()
                .in(EmpWorkHistory::getEmpId, ids));
        
        certificateMapper.delete(new LambdaQueryWrapper<EmpCertificate>()
                .in(EmpCertificate::getEmpId, ids));
    }

    @Override
    public List<EmpCertificate> getCertificateList(Long employeeId) {
        return certificateMapper.selectList(new LambdaQueryWrapper<EmpCertificate>()
                .eq(EmpCertificate::getEmpId, employeeId)
                .orderByDesc(EmpCertificate::getIssueDate));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveCertificate(EmpCertificate certificate) {
        if (certificate.getId() == null) {
            certificateMapper.insert(certificate);
        } else {
            certificateMapper.updateById(certificate);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteCertificate(Long id) {
        certificateMapper.deleteById(id);
    }

    @Override
    public List<EmpEducation> getEducationList(Long employeeId) {
        return educationMapper.selectList(new LambdaQueryWrapper<EmpEducation>()
                .eq(EmpEducation::getEmpId, employeeId)
                .orderByDesc(EmpEducation::getEndDate));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveEducation(EmpEducation education) {
        if (education.getId() == null) {
            educationMapper.insert(education);
        } else {
            educationMapper.updateById(education);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteEducation(Long id) {
        educationMapper.deleteById(id);
    }

    @Override
    public List<EmpWorkHistory> getWorkHistoryList(Long employeeId) {
        return workHistoryMapper.selectList(new LambdaQueryWrapper<EmpWorkHistory>()
                .eq(EmpWorkHistory::getEmpId, employeeId)
                .orderByDesc(EmpWorkHistory::getEndDate));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveWorkHistory(EmpWorkHistory workHistory) {
        if (workHistory.getId() == null) {
            workHistoryMapper.insert(workHistory);
        } else {
            workHistoryMapper.updateById(workHistory);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteWorkHistory(Long id) {
        workHistoryMapper.deleteById(id);
    }
    
    /**
     * 获取员工详情
     */
    public Employee getEmployeeDetail(Long employeeId) {
        return getById(employeeId);
    }
    
    /**
     * 新增员工信息
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean insertEmployee(Employee employee, List<EmpEducation> educationList, 
                                 List<EmpWorkHistory> workHistoryList, List<EmpCertificate> certificateList) {
        try {
            // 保存员工基本信息
            save(employee);
            Long employeeId = employee.getId();
            
            // 保存教育经历
            if (educationList != null && !educationList.isEmpty()) {
                for (EmpEducation education : educationList) {
                    education.setEmpId(employeeId);
                    educationMapper.insert(education);
                }
            }
            
            // 保存工作经历
            if (workHistoryList != null && !workHistoryList.isEmpty()) {
                for (EmpWorkHistory workHistory : workHistoryList) {
                    workHistory.setEmpId(employeeId);
                    workHistoryMapper.insert(workHistory);
                }
            }
            
            // 保存证书信息
            if (certificateList != null && !certificateList.isEmpty()) {
                for (EmpCertificate certificate : certificateList) {
                    certificate.setEmpId(employeeId);
                    certificateMapper.insert(certificate);
                }
            }
            
            return true;
        } catch (Exception e) {
            log.error("新增员工失败", e);
            return false;
        }
    }
    
    /**
     * 员工转正
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean confirmRegular(Long employeeId, Date regularDate) {
        try {
            Employee employee = getById(employeeId);
            if (employee == null) {
                return false;
            }
            
            // 更新员工状态为正式
            employee.setEmploymentStatus(1); // 1表示正式员工
            employee.setRegularDate(regularDate);
            updateById(employee);
            
            return true;
        } catch (Exception e) {
            log.error("员工转正失败", e);
            return false;
        }
    }
    
    /**
     * 员工离职
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean employeeLeave(Long employeeId, Date leaveDate, String leaveReason) {
        try {
            Employee employee = getById(employeeId);
            if (employee == null) {
                return false;
            }
            
            // 更新员工状态为离职
            employee.setEmploymentStatus(2); // 2表示离职员工
            // 这里假设Employee有leaveDate和leaveReason字段，如果没有需要添加
            // employee.setLeaveDate(leaveDate);
            // employee.setLeaveReason(leaveReason);
            updateById(employee);
            
            return true;
        } catch (Exception e) {
            log.error("员工离职失败", e);
            return false;
        }
    }
} 